<template>
  <el-row>
    <el-select
        v-model="blockId"
        filterable
        clearable
        placeholder="请选择模块"
        @change="blockChange"
    >
      <el-option
          v-for="item in dataBlock"
          :key="item.id"
          :label="item.isDefault === 1 ? '默认模块': item.blockName"
          :value="item.id"
      />
    </el-select>
  </el-row>
  <template v-for="item in dataProperty" :key="item.key">
    <el-row style="margin-bottom: 5px!important;">
      <el-text size="small">{{ item.name }}({{ item.identifier }})</el-text>
    </el-row>
    <el-row type="flex" align="middle">
      <el-col :span="20">
        <template
            v-if="item.specFunction.fieldType === 'int32' || item.specFunction.fieldType === 'float' || item.specFunction.fieldType === 'double'">
          <el-input
              v-model="property[item.identifier]"
              type="number"
              :min="item.specFunction.specMin"
              :max="item.specFunction.specMax"
              :step="item.specFunction.fieldType === 'int32' ? 1 : 0.1"
              :placeholder="`请输入${item.name} (${item.specFunction.fieldType})`"
          />
        </template>
        <template v-else-if="item.specFunction.fieldType === 'text'">
          <el-input
              v-model="property[item.identifier]"
              :placeholder="`请输入${item.name}`"
          />
        </template>
        <template v-else-if="item.specFunction.fieldType === 'enum'">
          <el-select
              v-model="property[item.identifier]"
              clearable
              placeholder="请选择">
            <el-option
                v-for="(option, index) in parseEnumOptions(item.specFunction.specEnum)"
                :key="index"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </template>
        <template v-else-if="item.specFunction.fieldType === 'bool'">
          <el-select v-model="property[item.identifier]" placeholder="请选择" clearable>
            <el-option :label="item.specFunction.specBoolTrue+'-1'" :value="1"/>
            <el-option :label="item.specFunction.specBoolFalse+'-0'" :value="0"/>
          </el-select>
        </template>
        <template v-else-if="item.specFunction.fieldType === 'array'">
          <template v-for="index in parseInt(item.specFunction.specSize)">
            <el-input
                v-model="property[item.identifier][index - 1]"
                :type="getType(item.specFunction.specItemType)"
                :placeholder="`请输入第${index}个${item.name}(${item.specFunction.specItemType})`"
            />
          </template>
        </template>
        <template v-else-if="item.specFunction.fieldType === 'struct'">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <span>{{ item.name }} 结构体内容</span>
            </div>
            <el-row>
              <el-col v-for="subItem in item.specFunction.specStruct" :key="subItem.key" :span="24">
                <template v-if="subItem.specFunction.fieldType === 'enum'">
                  <el-select
                      v-model="property[subItem.identifier]"
                      clearable
                      placeholder="请选择">
                    <el-option
                        v-for="(option, index) in parseEnumOptions(subItem.specFunction.specEnum)"
                        :key="index"
                        :label="option.label"
                        :value="option.value"
                    />
                  </el-select>
                </template>
                <template v-else-if="subItem.specFunction.fieldType === 'bool'">
                  <el-select v-model="property[subItem.identifier]" placeholder="请选择" clearable>
                    <el-option :label="subItem.specFunction.specBoolTrue+'-1'" :value="1"/>
                    <el-option :label="subItem.specFunction.specBoolFalse+'-0'" :value="0"/>
                  </el-select>
                </template>
                <template v-else-if="subItem.specFunction.fieldType === 'text'">
                  <el-input
                      v-model="property[subItem.identifier]"
                      :placeholder="`请输入${subItem.name}`"
                  />
                </template>
                <template v-else>
                  <el-input
                      v-model="property[subItem.identifier]"
                      type="number"
                      :min="subItem.specFunction.specMin"
                      :max="subItem.specFunction.specMax"
                      :step="subItem.specFunction.fieldType === 'int32' ? 1 : 0.1"
                      :placeholder="`请输入${subItem.name} (${subItem.specFunction.fieldType})`"
                  />
                </template>
              </el-col>
            </el-row>
          </el-card>
        </template>
        <template v-else>
          <el-input
              v-model="property[item.identifier]"
              :type="getType(item.specFunction.fieldType)"
              :placeholder="`请输入${item.name} (${item.specFunction.fieldType})`"
          />
        </template>
      </el-col>
      <el-col :span="4">
        <el-dropdown @command="handleCommand" class="margin-node">
          <span class="el-dropdown-link">
            调试<el-icon class="el-icon--right"><arrow-down/></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-upload" v-if="!downMode" :command="{action:'up', item}">上报
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-download" v-if="downMode" :command="{action:'get', item}">获取
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-setting" v-if="downMode && item.accessMode==='rw'"
                                :command="{action:'set', item}">设置
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
    </el-row>
  </template>
  <el-row v-if="!this.downMode">
    <el-button type="primary" @click="sendCommand">发送指令</el-button>
    <el-button @click="resetProperty">重置属性</el-button>
  </el-row>
</template>

<script>
import {validatenull} from "@/utils/validate";
import func from "@/utils/func";

export default {
  name: "simulatorProperty",
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
    downMode: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      property: {},
      blockId: '',
      dataBlock: [],
      dataProperty: [],
    };
  },
  watch: {
    modelValue() {
      if (validatenull(this.modelValue)) {
        return;
      }
      this.loadBlock();
    }
  },
  methods: {
    loadBlock() {
      this.dataBlock = this.modelValue.blocks;
      const defaultItem = this.dataBlock.find(item => item.isDefault === 1);
      if (!validatenull(defaultItem)) {
        this.blockId = defaultItem.id;
        this.loadProperty(this.blockId);
      }
    },
    blockChange(value) {
      this.blockId = value;
      this.loadProperty(this.blockId);
    },
    loadProperty(blockId) {
      this.dataProperty = this.modelValue.properties.filter(item => item.blockId === blockId);
      this.dataProperty.forEach(item => {
        if (item.specFunction.fieldType === 'array') {
          this.property[item.identifier] = Array(parseInt(item.specFunction.specSize)).fill('');
        } else {
          this.property[item.identifier] = '';
        }
      });
    },
    // 根据字段类型转换值
    convertValueByType(value, fieldType, itemType = null) {
      if (validatenull(value)) {
        return value;
      }
      if (fieldType === 'int32') {
        return parseInt(value, 10);
      } else if (fieldType === 'float' || fieldType === 'double') {
        return parseFloat(value);
      } else if (fieldType === 'bool') {
        return parseInt(value, 10) === 1;
      } else if (fieldType === 'enum') {
        const numValue = Number(value);
        return !isNaN(numValue) ? numValue : value;
      } else if (fieldType === 'array' && Array.isArray(value) && itemType) {
        return value.map(item => this.convertValueByType(item, itemType));
      }
      return value; // 默认返回原值（如text类型）
    },
    // 转换单个属性
    convertProperty(identifier, value) {
      const propertyItem = this.dataProperty.find(item => item.identifier === identifier);
      if (!propertyItem) {
        return value;
      }
      const fieldType = propertyItem.specFunction.fieldType;
      if (fieldType === 'array') {
        return this.convertValueByType(value, fieldType, propertyItem.specFunction.specItemType);
      }
      return this.convertValueByType(value, fieldType);
    },
    // 转换所有属性
    convertAllProperties(properties) {
      const result = {};
      for (const identifier in properties) {
        result[identifier] = this.convertProperty(identifier, properties[identifier]);
      }
      return result;
    },
    sendCommand() {
      const propertyData = func.filterEmptyObject(this.property);
      if (validatenull(propertyData)) {
        this.$message.warning('请填写属性数据');
        return;
      }
      const data = this.convertAllProperties(propertyData);
      this.$emit('sendCommand', data);
    },
    resetProperty() {
      this.property = {};
    },
    reloadProperty(item) {
      this.property = {
        ...this.property,
        ...item
      }
    },
    getType(type) {
      return type === 'text' ? 'text' : 'number';
    },
    parseEnumOptions(specEnum) {
      return specEnum.split(';').map(option => {
        const [value, label] = option.split(':');
        return {value, label: label + "-" + value};
      });
    },
    handleCommand(command) {
      const action = command.action;
      const item = command.item;
      console.log("@action:" + action);
      console.log((item));
      if (command.action === 'up') {
        const property = this.property?.[item.identifier];
        if (validatenull(property)) {
          this.$message.warning('请填写属性数据');
          return;
        }
        const convertedValue = this.convertValueByType(property, item.specFunction.fieldType);
        const data = {
          [item.identifier]: convertedValue
        };
        this.$emit('sendCommand', data);
      } else if (command.action === 'get') {
        const data = [item.identifier];
        this.$emit('sendCommand', data, command.action);
      } else if (command.action === 'set') {
        const property = this.property?.[item.identifier];
        if (validatenull(property)) {
          this.$message.warning('请填写属性数据');
          return;
        }
        const convertedValue = this.convertValueByType(property, item.specFunction.fieldType);
        const data = {
          [item.identifier]: convertedValue
        };
        this.$emit('sendCommand', data, command.action);
      }
    }
  }
}
</script>
<style scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  text-align: center;
}

.margin-node {
  margin-left: 12px;
}
</style>
